package cn.daniellee.plugin.pl.listener;

import cn.daniellee.plugin.pl.PortalLimiter;
import org.bukkit.Bukkit;
import org.bukkit.block.Block;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.block.BlockPlaceEvent;
import org.bukkit.event.entity.EntityPortalEvent;
import org.bukkit.event.player.PlayerPortalEvent;
import org.bukkit.event.world.PortalCreateEvent;

import java.util.List;

public class PortalListener implements Listener {

	@EventHandler
	public void onBlockPlace(BlockPlaceEvent e) {
		if (!e.getPlayer().isOp() && "world_nether".equals(e.getBlock().getLocation().getWorld().getName()) && e.getBlock().getLocation().getBlockY() > 126) {
			if (PortalLimiter.getInstance().isNetherTopProtect()) {
				e.getBlock().getWorld().getNearbyEntities(e.getBlock().getLocation(), 10,10 ,10).forEach(item -> {
					if (item.getType().toString().equals("PLAYER")) {
						item.sendMessage((PortalLimiter.getInstance().getPrefix() + PortalLimiter.getInstance().getConfig().getString("build-deny", "Construction is prohibited outside the top of nether.")).replace("&", "§"));
					}
				});
				e.setCancelled(true);
			}
		}
	}

	@EventHandler
	public void onPortalCreate(PortalCreateEvent e) {
		if (e.getBlocks().stream().filter(item -> "NETHER_PORTAL".equals(item.getType().name())).count() > PortalLimiter.getInstance().getMaxSize()) {
			e.setCancelled(true);
			e.getBlocks().get(0).getWorld().getNearbyEntities(e.getBlocks().get(0).getLocation(), 10,10 ,10).forEach(item -> {
				if ("PLAYER".equals(item.getType().name())) {
					item.sendMessage((PortalLimiter.getInstance().getPrefix() + PortalLimiter.getInstance().getConfig().getString("size-limit", "Nether gate size exceeds limit.")).replace("&", "§"));
				}
			});
		}
	}

	@EventHandler
	public void onPlayerPortal(PlayerPortalEvent e) {
		List<String> currentList = PortalLimiter.getInstance().getConfig().getStringList("allow-type");
		if (!currentList.contains("PLAYER")) {
			e.getPlayer().sendMessage((PortalLimiter.getInstance().getPrefix() + PortalLimiter.getInstance().getConfig().getString("player-forbid", "This service has banned players from passing the portal.")).replace("&", "§"));
			e.setCancelled(true);
		}
	}

	@EventHandler
	public void onEntityPortal(EntityPortalEvent e) {
		List<String> currentList = PortalLimiter.getInstance().getConfig().getStringList("allow-type");
		if (!currentList.contains(e.getEntityType().toString())) {
			e.setCancelled(true);
		}
	}
}
